package org.jradweb.core.web;

import java.beans.PropertyEditor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

/**
 * 
 * 
 * Created On 2008-7-9
 * 
 * @author <a href="mailto:wagzhi@gmail.com">Paul Wang</a>
 * @version $Id: WebDataBinderImpl.java 149 2008-10-10 03:10:10Z wagzhi $
 */
public class WebDataBinderImpl implements WebDataBinder {
	private Map<Class ,Class> customPopertyEditors=new HashMap<Class,Class>();
	
	public WebDataBinderImpl() {

	}

	public Map<Class, Class> getCustomPopertyEditors() {
		return customPopertyEditors;
	}

	public void setCustomPopertyEditors(
		Map<Class, Class> customPopertyEditors) {
		this.customPopertyEditors = customPopertyEditors;
	}

	public <T> FormBean<T> bind(T target, HttpServletRequest request) {

		FormBeanImpl<T> bean = new FormBeanImpl<T>(target,request.getLocale());
		for(Class clazz:customPopertyEditors.keySet()){
			try {
				bean.registerCustomEditor(clazz, (PropertyEditor)this.customPopertyEditors.get(clazz).newInstance());
			} catch (InstantiationException e) {
				throw new IllegalArgumentException(e);
			} catch (IllegalAccessException e) {
				throw new IllegalArgumentException(e);
			}
		}
		
		// get parameter keys for target bean
		List<String> keys = new ArrayList<String>();
		for (Object key : request.getParameterMap().keySet()) {
			//TODO need get file or string[]
			String value = request.getParameter((String)key);
			value=StringUtils.trimToNull(value);
			bean.setPropertyValue((String) key, value);

		}
		bean.validator();
		return bean;
	}

	public <T> FormBean<T> wrap(T target,Locale locale) {
		FormBeanImpl<T> bean = new FormBeanImpl<T>(target,locale);
		return bean;
	}
	
	public void bind(Object target, Map<String, Object> map) {
		// TODO Auto-generated method stub

	}


}
